package com.ayic.garbagerecycle.controller;

import com.ayic.garbagerecycle.pojo.MultipartInputStreamFileResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import com.ayic.garbagerecycle.pojo.Result;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @author AyiC416
 * @ClassName garbagerecycle
 * @date 2025/5/21
 * @Description TODO
 */

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping("/image")
@RestController
public class ClassifyController {

    @PostMapping("/classify")
    public Result classifyImage(@RequestParam("file") MultipartFile file) {
        try {
            // 将 MultipartFile 转为 HttpEntity 发送给 Flask
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", new MultipartInputStreamFileResource(file.getInputStream(), file.getOriginalFilename()));

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            RestTemplate restTemplate = new RestTemplate();
            String flaskUrl = "http://localhost:5000/predict";

            ResponseEntity<Map> response = restTemplate.postForEntity(flaskUrl, requestEntity, Map.class);

            return Result.success(response.getBody()); // 使用你的统一响应封装
        } catch (Exception e) {
            return Result.error("识别失败: " + e.getMessage());
        }
    }
}
